"""
    1. 实例化人脸和眼睛检测的分类器对象
        classifier = cv.CascadeClassifier("haarcascade_frontalface_default.xml")
    2. 加载分类器
        classifier.load("haarcascade_frontalface_default.xml")
    3. 进行人脸和眼睛的检测
        rect = classifier.detectMultiScale(gray, scaleFactor, minNeighbors, minSize, maxsize)
            参数：
                Gray:要进行检测的人脸图像，
                scaleFactor：前后两次扫描，搜索窗口的比例系数，
                minneighbors:目标至少被检测到minNeighbors次才会被认为是目标
                minsize和maxsize:目标的最小尺寸和最大尺寸
"""
import cv2 as cv
import matplotlib.pyplot as plt

print(cv.__file__)
# 1. 以灰度图的形式读取图片
img = cv.imread("image/yangzi.jpg")
gray = cv.cvtColor(img, cv.COLOR_BGRA2GRAY)

# 2. 实例化Opencv人脸和眼睛识别的分类器
face_cas = cv.CascadeClassifier("C:/Users/Chengqs/AppData/Local/Programs/Python/Python310/lib/site-packages/cv2/data/haarcascade_frontalface_default.xml")
face_cas.load("C:/Users/Chengqs/AppData/Local/Programs/Python/Python310/lib/site-packages/cv2/data/haarcascade_frontalface_default.xml")

eyes_cas = cv.CascadeClassifier("C:/Users/Chengqs/AppData/Local/Programs/Python/Python310/lib/site-packages/cv2/data/haarcascade_eye.xml")
eyes_cas.load("C:/Users/Chengqs/AppData/Local/Programs/Python/Python310/lib/site-packages/cv2/data/haarcascade_eye.xml")

# 3. 调用识别人脸
faceRects = face_cas.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=3, minSize=(32, 32))
for faceRect in faceRects:
    x, y, w, h = faceRect
    # 框出人脸
    cv.rectangle(img, (x, y), (x + h, y + w), (0, 0, 255), 3)
    # 4. 在识别出的人脸中进行眼睛的检测
    roi_color = img[y:y+h, x:x+w]
    roi_gray = gray[y:y+h, x:x+w]
    eyes = eyes_cas.detectMultiScale(roi_gray)
    for (ex, ey, ew, eh) in eyes:
        cv.rectangle(roi_color, (ex, ey), (ex + ew, ey + eh), (0, 0, 255), 2)

# 5. 检测结果的绘制
plt.figure(figsize=(8, 6), dpi=100)
plt.imshow(img[:, :, ::-1]), plt.title("检测结果")
plt.xticks([]), plt.yticks([])
plt.show()




